package com.lcm.openapi.common.exception;


import com.lcm.openapi.common.models.api.Result;
import com.lcm.openapi.common.models.api.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lichuanming
 * 全局异常捕获
 */
@Slf4j
@RestControllerAdvice
public class DefaultGlobalExceptionHandlerAdvice {

    /**
     * 参数缺失
     */
    @ExceptionHandler(value = {MissingServletRequestParameterException.class})
    public Result missingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("missing servlet request parameter exception:{}", e);
        return Result.fail(ResultCode.PARAMETER_NOT_FOUND);
    }

    /**
     * 参数验证异常
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("methodArgumentNotValidException:{}", e);
        return Result.fail(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 集中捕获业务异常，异常提示按业务代码中定义的抛出
     */
    @ExceptionHandler(value = {ServiceException.class})
    public Result serviceException(ServiceException e) {
        log.warn("Service exception:{}", e);
        return Result.fail(e.getErrorType() ,e.getMessage());
    }

    /**
     * 其他异常
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result exception(Exception ex) {
        log.error("exception:{}", ex);
        return Result.fail(ResultCode.ERROR);
    }
}